import Router from 'koa-router';
import { Context } from 'koa';
import { DeepSeekService } from '../services/deepseekService';

export const deepseekRouter = new Router({ prefix: '/api/deepseek' });

const deepseekService = new DeepSeekService();

/**
 * 流式聊天接口
 * POST /api/deepseek/chat/stream
 */
deepseekRouter.get('/chat/stream', async (ctx: Context) => {
  const { content } = ctx.request.query as { content: string };

  if (!content || typeof content !== 'string') {
    ctx.status = 400;
    ctx.body = {
      error: true,
      message: '请提供有效的content参数'
    };
    return;
  }

  // 设置SSE响应头
  ctx.set({
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'Access-Control-Allow-Origin': ctx.headers.origin || '*', // 动态允许请求来源
    'Access-Control-Allow-Credentials': 'true',
    'Access-Control-Expose-Headers': '*',
  });

  ctx.status = 200;

  // 创建一个可写流
  const stream = ctx.res;

  // 发送初始连接确认
  stream.write(`data: ${JSON.stringify({ type: 'connected', message: '连接成功，开始处理...' })}\n\n`);

  try {
    await deepseekService.streamChat(
      content,
      // onData callback
      (chunk: string) => {
        const data = JSON.stringify({
          type: 'content',
          content: chunk,
          timestamp: new Date().toISOString()
        });
        console.log('onData', data)
        stream.write(`data: ${data}\n\n`);
      },
      // onError callback
      (error: Error) => {
        const data = JSON.stringify({
          type: 'error',
          message: error.message,
          timestamp: new Date().toISOString()
        });
        console.log('onError', data)
        stream.write(`data: ${data}\n\n`);
        stream.write(`data: [DONE]\n\n`);
        stream.end();
      },
      // onEnd callback
      () => {
        const data = JSON.stringify({
          type: 'done',
          message: '响应完成',
          timestamp: new Date().toISOString()
        });
        console.log('onEnd', data)
        stream.write(`data: ${data}\n\n`);
        stream.write(`data: [DONE]\n\n`);
        stream.end();
      }
    );
  } catch (error: any) {
    const data = JSON.stringify({
      type: 'error',
      message: error.message,
      timestamp: new Date().toISOString()
    });
    console.log('onError', data)
    stream.write(`data: ${data}\n\n`);
    stream.write(`data: [DONE]\n\n`);
    stream.end();
  }
});

/**
 * 普通聊天接口
 * POST /api/deepseek/chat
 */
deepseekRouter.post('/chat', async (ctx: Context) => {
  const { content } = ctx.request.body as { content: string };

  if (!content || typeof content !== 'string') {
    ctx.status = 400;
    ctx.body = {
      error: true,
      message: '请提供有效的content参数'
    };
    return;
  }

  try {
    const response = await deepseekService.chat(content);

    ctx.body = {
      success: true,
      data: {
        content: response,
        timestamp: new Date().toISOString()
      }
    };
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      error: true,
      message: error.message,
      timestamp: new Date().toISOString()
    };
  }
});

/**
 * 获取API状态
 * GET /api/deepseek/status
 */
deepseekRouter.get('/status', (ctx: Context) => {
  ctx.body = {
    status: 'ok',
    service: 'DeepSeek API',
    endpoints: {
      stream: '/api/deepseek/chat/stream',
      chat: '/api/deepseek/chat'
    },
    timestamp: new Date().toISOString()
  };
}); 